package la.renzhen.rtpt.config.source;

import la.renzhen.rtpt.config.ConfigurationSource;
import la.renzhen.rtpt.config.Reloadable;
import lombok.Getter;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *
 * @author <a href="mailto:zhouhaichao@2008.sina.com">haiker</a>
 * @version 30/05/2018 12:55 AM
 */
public class CachedConfigurationSource implements ConfigurationSource, Reloadable {

    String environment;

    String prefix;

    @Getter
    ConfigurationSource configurationSource;

    Map<String, String> cache = new HashMap<>();

    public CachedConfigurationSource(String environment, String prefix, ConfigurationSource source) {
        this.environment = environment;
        this.prefix = prefix;
        this.configurationSource = source;
    }

    @Override
    public Map<String, String> loadAll(String environment, String prefix) {
        return cache;
    }

    @Override
    public String get(String environment, String key) {
        return cache.get(key);
    }

    @Override
    public void reload() {
        synchronized (this) {
            cache = configurationSource.loadAll(environment, prefix);
        }
    }
}
